﻿using Microsoft.SqlServer.Server;
using System;
using System.Data.SqlTypes;
using System.Text;

[Serializable]
[SqlUserDefinedAggregate(
    Format.UserDefined,
    IsInvariantToDuplicates = false,
    IsInvariantToNulls = true,
    IsInvariantToOrder = false,
    MaxByteSize = 8000,
    Name = "GroupConcat")]
public struct AggGroupConcat : IBinarySerialize
{
    private StringBuilder stringBuilder;

    /// <summary>
    /// 查询处理器使用此方法初始化聚合的计算
    /// </summary>
    public void Init()
    {
        stringBuilder = new StringBuilder();
    }

    /// <summary>
    /// 查询处理器使用此方法累计聚合值
    /// </summary>
    /// <param name="value"></param>
    public void Accumulate(SqlString Value, SqlString  )
    {
        stringBuilder.Append(string.Format("{0},", Value));
    }

    /// <summary>
    /// 查询处理器使用此方法合并聚合的多个部分计算的值
    /// </summary>
    /// <param name="Group"></param>
    public void Merge(AggGroupConcat Group)
    {
        stringBuilder.Append(Group.stringBuilder);
    }

    /// <summary>
    /// 此方法用于返回完成聚合计算的结果
    /// </summary>
    /// <returns></returns>
    public SqlString Terminate()
    {
        return new SqlString(stringBuilder.ToString());
    }

    #region Implement interface IBinarySerialize
    /// <summary>
    /// 读
    /// </summary>
    /// <param name="r"></param>
    public void Read(System.IO.BinaryReader r)
    {
        stringBuilder = new StringBuilder(r.ReadString());
    }

    /// <summary>
    /// 写
    /// </summary>
    /// <param name="w"></param>
    public void Write(System.IO.BinaryWriter w)
    {
        w.Write(stringBuilder.ToString());
    }
    #endregion
}